﻿#include "signupwidget.h"
#include "ui_signupwidget.h"
#include <QIcon>
#include <QFileDialog>

SignUpWidget::SignUpWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SignUpWidget)
{
    ui->setupUi(this);
    setWindowTitle("注册界面");
    setWindowIcon(QIcon(":/images/image/1.jpg"));

    connect(ui->avator, SIGNAL(clicked()), this, SLOT(selectAvator()));
    connect(ui->signup, SIGNAL(clicked()), this, SLOT(signUp()));
    connect(TRANS->getSignalGun(), SIGNAL(reSignUpAvator(InfoHead*,
                                 QJsonDocument, QHostAddress, quint16)),
        this, SLOT(reAvator(InfoHead* info, QJsonDocument doc, QHostAddress ip, quint16 port)));
    connect(TRANS->getSignalGun(), SIGNAL(reSignUpInfo(InfoHead*,
                                 QJsonDocument, QHostAddress, quint16)),
            this, SLOT(reSignUp(InfoHead* info, QJsonDocument doc, QHostAddress ip, quint16 port)));
}

SignUpWidget::~SignUpWidget()
{
    delete ui;
}

void SignUpWidget::selectAvator() {
    QFile file(QFileDialog::getOpenFileName(this));
    file.open(QIODevice::ReadOnly);

    bytes = file.readAll();
}

void SignUpWidget::signUp() {
    TRANS->writeTcp(new InfoHead(bytes.size(), 1, Operation::SignUpAvator,
                     Operation::Success, 0, 0,
                     QString("")),
            bytes,
            CONF.serverIp, CONF.tcpPort);

    }

void SignUpWidget::reSignUp(InfoHead *infoHead,
                              QJsonDocument doc, QHostAddress ip, quint16 port){
    //TODO:
}

void SignUpWidget::reAvator(InfoHead *reInfoHead,
                QJsonDocument reDoc, QHostAddress ip, quint16 port) {
    QJsonDocument doc;
    QJsonObject obj;

    if (ui->man->isChecked()) {
        obj.insert("gender", "男");
    }
    else {
        obj.insert("gender", "女");
    }

    obj.insert("avator", reDoc.object()["path"]);
    obj.insert("account", ui->account->text());
    obj.insert("password", ui->password->text());
    obj.insert("name", ui->name->text());
    obj.insert("email", ui->email->text());
    obj.insert("age", ui->age->text());
    obj.insert("phone_number", ui->phonenumber->text());
    obj.insert("signature", ui->signature->text());
    obj.insert("level", 1);

    doc.setObject(obj);

    QByteArray infoBytes = doc.toJson();
    int fileSize = infoBytes.size();

    InfoHead *infoHead = new InfoHead(fileSize, 0, Operation::SignUpInfo, Operation::Success,
                                      0, 0, QString(""));
    TRANS->writeUdp(infoHead, infoBytes, ip, port);
}
